import { defineStore } from "pinia";
import {
  type userType,
  store,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import {
  type UserResult,
  type RefreshTokenResult,
  getLogin,
  getLogout,
  refreshTokenApi,
  switchDomainApi
} from "@/api/user";
import { useMultiTagsStoreHook } from "./multiTags";
import {
  type DataInfo,
  setToken,
  removeToken,
  userKey,
  switchDomain
} from "@/utils/auth";
import { message } from "@/utils/message";

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    // 租户
    domainId: storageLocal().getItem<DataInfo>(userKey)?.domainId ?? "2",
    // 头像
    avatar: storageLocal().getItem<DataInfo>(userKey)?.avatar ?? "",
    // 用户名
    username: storageLocal().getItem<DataInfo>(userKey)?.username ?? "",
    // 昵称
    nickname: storageLocal().getItem<DataInfo>(userKey)?.nickname ?? "",
    // 页面级别权限
    roles: storageLocal().getItem<DataInfo>(userKey)?.roles ?? [],
    // 是否勾选了登录页的免登录
    isRemembered: false,
    // 登录页的免登录存储几天，默认7天
    loginDay: 7
  }),
  actions: {
    SET_DOMAIN(domainId: string) {
      this.domainId = domainId;
    },
    GET_DOMAIN(): string {
      return this.domainId;
    },
    /** 存储头像 */
    SET_AVATAR(avatar: string) {
      this.avatar = avatar;
    },
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储昵称 */
    SET_NICKNAME(nickname: string) {
      this.nickname = nickname;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 存储是否勾选了登录页的免登录 */
    SET_ISREMEMBERED(bool: boolean) {
      this.isRemembered = bool;
    },
    /** 设置登录页的免登录存储几天 */
    SET_LOGINDAY(value: number) {
      this.loginDay = Number(value);
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<UserResult>((resolve, reject) => {
        getLogin(data)
          .then(data => {
            if (data) setToken(data);
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    async logOut() {
      return new Promise((resolve, reject) => {
        getLogout()
          .then(succeed => {
            if (succeed) {
              this.domainId = "";
              this.username = "";
              this.roles = [];
              removeToken();
              useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
              resetRouter();
              message("退出登录成功.", { type: "success" });
              resolve(succeed);
            }
            // 失败
            else {
              reject("退出登录调用失败");
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 切换业务域 */
    async switchToDomain(domainId: string) {
      return new Promise((resolve, reject): void => {
        switchDomainApi(domainId)
          .then(data => {
            if (data) {
              setToken(data);
              resolve(data);
            } else {
              reject("切换业务域失败");
            }
          })
          .catch(error => {
            reject(error);
          });
      });
      // 先仅前端切换业务域，后面请求后端生成完整token，用完整token进行域的切换
      switchDomain(domainId);
    },
    /** 刷新`token` */
    async handRefreshToken(data) {
      return new Promise<RefreshTokenResult>((resolve, reject) => {
        refreshTokenApi(data)
          .then(data => {
            if (data) {
              setToken(data);
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
